<template>
  <div class="page-container">
    <el-card class="main-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="header-title">电子票据上传医保系统</span>
        <el-divider direction="vertical" class="header-divider"></el-divider>
        <span class="header-desc">支持批量上传PDF格式电子票据，单个文件不超过10MB</span>
      </div>

      <el-form :inline="true" :model="form" class="search-form">
        <!-- 机构选择 -->
        <el-form-item>
          <el-select
              v-model="queryParams.ID_ORG"
              placeholder="请选择机构"
              style="width: 200px"
              clearable
              class="form-select">
            <el-option
                v-for="item in provinceOptions"
                :key="item.ID_ORG"
                :label="item.NA"
                :value="item.ID_ORG"/>
          </el-select>
        </el-form-item>

        <!-- 日期组件 -->
        <el-form-item>
          <el-date-picker
              v-model="queryParams.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="changeDate"
              class="date-picker"
              clearable>
          </el-date-picker>
        </el-form-item>

        <!-- 上传按钮区域 -->
        <el-form-item class="upload-btn-group">
          <el-button
              type="success"
              @click="electronicBillsUplodYB()"
              :disabled="fileList.length === 0"
              :loading="uploading"
              class="primary-btn"
              style="color: #000 !important">
            <i class="el-icon-upload" v-if="!uploading"></i>
            <i class="el-icon-loading" v-if="uploading"></i>
            电子票据上传医保
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 中间区域：文件列表展示 -->
      <div class="file-list-section">
        <div v-if="fileList.length > 0" class="file-list-container">
          <div class="list-header">
            <span class="list-title">已选文件</span>
            <el-button
                type="text"
                size="mini"
                class="clear-btn"
                @click="fileList = []">
              清空
            </el-button>
          </div>

          <el-scrollbar class="file-scroll">
            <div class="file-item" v-for="file in fileList" :key="file.uid">
              <i class="el-icon-file-pdf file-icon"></i>
              <div class="file-info">
                <div class="file-name ellipsis">{{ file.name }}</div>
                <div class="file-size">{{ formatFileSize(file.size) }}</div>
              </div>
              <!-- 新增预览按钮 -->
              <el-button
                  type="text"
                  size="mini"
                  class="preview-btn"
                  @click="handleFilePreview(file)">
                <i class="el-icon-view"></i>
              </el-button>
              <el-button
                  type="text"
                  size="mini"
                  class="remove-btn"
                  @click="handleFileRemove(file, fileList)">
                <i class="el-icon-delete"></i>
              </el-button>
            </div>

            <!-- 底部数量统计行 -->
            <div class="file-count-footer">
              <span class="count-text">共 {{ fileList.length }} 个文件</span>
              <span class="total-size">总大小: {{ calculateTotalSize() }}</span>
            </div>
          </el-scrollbar>
        </div>

        <!-- 无文件时的提示 -->
        <div v-else class="empty-file-hint">
          <i class="el-icon-file-text-o"></i>
          <p>暂无选中的文件，请点击下方加号添加文件</p>
        </div>
      </div>

      <!-- 上传进度条 -->
      <el-progress v-if="uploadProgress > 0 && uploadProgress < 100"
                   :percentage="uploadProgress"
                   stroke-width="4"
                   class="progress-bar"
                   stroke-linecap="round"
      ></el-progress>

      <!-- 底部区域：加号上传框 -->
      <div class="bottom-upload-area">
        <el-upload
            class="plus-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="100"
            :on-exceed="handleExceed"
            accept=".pdf"
            multiple
            drag
            :show-file-list="false">
          <div class="plus-icon-container">
            <i class="el-icon-plus upload-plus-icon"></i>
            <span class="upload-tip">点击或拖拽文件到此处</span>
          </div>
        </el-upload>
      </div>
    </el-card>

    <!-- PDF预览弹窗 -->
    <el-dialog
        title="PDF预览"
        :visible.sync="previewVisible"
        width="80%"
        :before-close="handleClosePreview"
        append-to-body>
      <div class="pdf-preview-container" v-if="previewUrl">
        <embed
            :src="previewUrl"
            type="application/pdf"
            width="100%"
            height="600px"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'electronic-bill-upload',
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 86400000;
        }
      },
      queryParams: {
        ID_ORG: '68401005caaa060001b96f9f',
        date: []
      },
      provinceOptions: [{
        ID_ORG: '68401005caaa060001b96f9f',
        NA: '平昌县中医医院'
      }],
      form: {},
      fileList: [],
      uploadProgress: 0,
      uploading: false,
      // 新增预览相关变量
      previewVisible: false,
      previewUrl: ''
    }
  },
  mounted() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth();
    const firstDay = new Date(currentYear, currentMonth, 1);
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    this.queryParams.date = [firstDay, lastDay];
  },
  methods: {
    changeDate() {
    },

    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) return size + ' B';
      if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
      return (size / (1024 * 1024)).toFixed(2) + ' MB';
    },

    // 计算总文件大小
    calculateTotalSize() {
      const totalSize = this.fileList.reduce((total, file) => total + file.size, 0);
      return this.formatFileSize(totalSize);
    },

    // 处理文件添加（支持多文件）
    handleFileChange(file, fileList) {
      // 验证文件大小
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error(`文件 ${file.name} 大小超过10MB，请重新选择`);
        this.fileList = fileList.filter(f => f.uid !== file.uid);
        return;
      }
      this.fileList = fileList;
    },

    // 处理文件移除
    handleFileRemove(file, fileList) {
      // 过滤掉当前要删除的文件（通过唯一标识 uid 区分）
      this.fileList = fileList.filter(item => item.uid !== file.uid);

      // 如果删除的是正在预览的文件，关闭预览
      if (this.previewUrl && (file.url === this.previewUrl || (file.raw && URL.createObjectURL(file.raw) === this.previewUrl))) {
        this.handleClosePreview();
      }
    },

    // 处理文件超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传100个文件，本次已选择 ${files.length} 个，将忽略超出部分`);
      this.fileList = fileList;
    },

    // 上传逻辑
    async electronicBillsUplodYB() {
      if (!this.queryParams.date || this.queryParams.date.length !== 2) {
        this.$message.warning('请选择完整的日期范围');
        return;
      }

      if (this.fileList.length === 0) {
        this.$message.warning('请选择要上传的PDF文件');
        return;
      }

      this.uploading = true;
      this.uploadProgress = 0;

      const interval = setInterval(() => {
        this.uploadProgress += 5;
        if (this.uploadProgress >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            this.uploading = false;
            this.uploadProgress = 0;
            this.$message.success('文件上传成功');
            this.fileList = [];
          }, 500);
        }
      }, 300);
    },

    // 新增：处理PDF预览
    handleFilePreview(file) {
      // 如果是已上传的文件（有远程URL）
      if (file.url) {
        this.previewUrl = file.url;
        this.previewVisible = true;
      }
      // 如果是本地选择的未上传文件（通过File对象生成临时URL）
      else if (file.raw) {
        // 创建本地文件的临时预览URL
        this.previewUrl = URL.createObjectURL(file.raw);
        this.previewVisible = true;
      } else {
        this.$message.warning('无法预览该文件');
      }
    },

    // 新增：关闭预览弹窗时释放临时URL（避免内存泄漏）
    handleClosePreview() {
      this.previewVisible = false;
      // 如果是本地临时URL，需要手动释放
      if (this.previewUrl && this.previewUrl.startsWith('blob:')) {
        URL.revokeObjectURL(this.previewUrl);
        this.previewUrl = '';
      }
    }
  },
  // 组件销毁时确保释放所有临时URL
  beforeDestroy() {
    if (this.previewUrl && this.previewUrl.startsWith('blob:')) {
      URL.revokeObjectURL(this.previewUrl);
    }
  }
}
</script>

<style scoped>
/* 穿透 scoped 限制，修改拖拽容器的宽高 */
::v-deep .el-upload-dragger {
  width: 130px !important;
  height: 60px !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  min-height: 500px;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: #f9fafb;
  border-bottom: 1px solid #eee;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
}

.header-divider {
  margin: 0 12px;
  height: 16px;
}

.header-desc {
  font-size: 14px;
  color: #6b7280;
}

.search-form {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  border-bottom: 1px dashed #eee;
}

.form-select, .date-picker {
  border-radius: 6px;
  transition: border-color 0.2s;
}

.form-select:hover, .date-picker:hover {
  border-color: #409eff;
}

.upload-btn-group {
  margin-left: auto;
}

.primary-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s;
}

.primary-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 中间区域：文件列表展示 */
.file-list-section {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.empty-file-hint {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 40px 0;
}

.empty-file-hint i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.file-list-container {
  flex: 1;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background-color: #f9fafb;
  border-bottom: 1px solid #eee;
}

.list-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2329;
}

.clear-btn {
  color: #6b7280;
  padding: 4px 8px;
}

.clear-btn:hover {
  color: #f56c6c;
}

.file-scroll {
  flex: 1;
  max-height: none;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  transition: background-color 0.2s;
}

.file-item:hover {
  background-color: #f9fafb;
}

.file-icon {
  color: #f56c6c;
  font-size: 16px;
  margin-right: 12px;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  color: #1f2329;
  margin-bottom: 2px;
}

.file-size {
  font-size: 12px;
  color: #6b7280;
}

/* 预览按钮样式 */
.preview-btn {
  color: #409eff;
  padding: 4px;
  margin-right: 4px;
  transition: all 0.2s;
}

.preview-btn:hover {
  color: #1890ff;
}

.remove-btn {
  color: #9ca3af;
  padding: 4px;
  transition: all 0.2s;
}

.remove-btn:hover {
  color: #f56c6c;
}

/* 底部数量统计行 */
.file-count-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  font-size: 13px;
  color: #6b7280;
  border-top: 1px dashed #eee;
  margin-top: 5px;
}

.count-text {
  font-weight: 500;
}

.total-size {
  font-size: 12px;
}

/* 底部区域：加号上传框 */
.bottom-upload-area {
  padding: 10px;
  border-top: 1px dashed #eee;
  display: flex;
  justify-content: center;
}

.plus-upload {
  width: 130px;
  height: 60px;
  border-radius: 4px;
  border: 1px dashed #d0d7de;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  transition: all 0.3s ease;
  background-color: #fcfcfc;
}

.plus-upload:hover {
  border-color: #409eff;
  background-color: #b11549;
}

.plus-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-plus-icon {
  font-size: 30px;
  color: #409eff;
  margin-bottom: 2px;
}

.upload-tip {
  font-size: 12px;
  color: #6b7280;
  white-space: nowrap;
}

/* 进度条样式 */
.progress-bar {
  margin: 0 20px 15px;
  width: calc(100% - 40px);
}

/* PDF预览容器样式 */
.pdf-preview-container {
  width: 100%;
  overflow: hidden;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .upload-btn-group {
    margin-left: 0;
    width: 100%;
  }

  .primary-btn {
    width: 100%;
  }
}
</style>